<template>
  <el-table-column class-name="order-table-col">
    <template #default="scope">
      <ContentWrap
        :bodyStyle="{ padding: '10px', borderRadius: '0px' }"
        class="!border-rd-none !border-b-none mb-0! bg-[var(--el-table-header-bg-color)]!"
      >
        <el-row
          class="color-[#606266] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
          :justify="'space-between'"
        >
          <el-col :span="21">
            <div class="flex flex-wrap">
              <span>订单号码：{{ scope.row.no }}</span>
              <span class="ml-10px">销售时间：{{ formatDate(scope.row.tradeTime) }}</span>
              <template v-if="scope.row.deliveryType === DeliveryTypeEnum.SHOP.type">
                <span class="ml-10px">销售门店： </span>
                <el-tag>{{ scope.row.nodeName }}</el-tag>
                <span class="ml-10px">销售员工： </span>
                <template v-if="scope.row.employeeStr && scope.row.employeeStr.length > 0">
                  <el-tag class="mr-5px!" v-for="item in scope.row.employeeStr" :key="item">{{
                    item.employeeName
                  }}</el-tag>
                </template>
              </template>

              <!-- <el-image
                v-if="scope.row?.user?.activeState == 1"
                class="w-26px"
                src="https://files.meton.vip/6aa306a95ea11ed10973123b535247f84da11d1b385389e6ed5e5f872a67ce07.png" />
              <span class="ml-10px">手机号码：{{ scope.row?.user?.mobile }}</span> -->
              <span class="ml-10px">操作时间：{{ formatDate(scope.row.updateTime) }}</span>
              <span class="ml-10px">订单类型：</span
              ><dict-tag :type="DICT_TYPE.TRADE_ORDER_TYPE" :value="scope.row.type" />
              <span class="ml-10px">代理名称：</span>
              <el-tag>{{ scope.row?.user?.nickname }}</el-tag>
            </div>
          </el-col>
          <el-col :span="3">
            <slot name="rightOperate" :row="scope.row"></slot>
          </el-col>
        </el-row>
      </ContentWrap>
      <el-table
        :ref="setOrderTableRef"
        :border="true"
        :data="scope.row.items"
        :row-class-name="'table-col-row-class'"
        :span-method="spanMethod"
        style="width: 100%"
      >
        <el-table-column min-width="260" align="center" prop="spuName" label="商品信息">
          <template #default="{ row }">
            <div class="flex">
              <div class="flex items-center">
                <div class="mr-[10px] flex items-center">
                  <el-image
                    :src="row.picUrl"
                    class="!h-[48px] !w-[48px] border-rd-4px"
                    @click="imagePreview(row.picUrl)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <icon icon="ep:picture" />
                      </div>
                    </template>
                  </el-image>
                </div>

                <el-tooltip :content="row.spuName" placement="top">
                  <span class="text-left overflow-hidden">
                    <meton-tag
                      v-if="row?.sales"
                      :is-dict="false"
                      class="mr-5px"
                      effect="dark"
                      type="danger"
                      color="#ff0000"
                      :value="'赠品'"
                    />
                    <meton-tag
                      v-if="row?.spuType == 2"
                      :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE2"
                      :value="row?.skuType"
                      effect="plain"
                    />
                    <meton-tag
                      v-else-if="row?.spuType == 4"
                      :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE4"
                      :value="row?.skuType"
                      effect="plain"
                    />
                    <meton-tag
                      :dict-type="DICT_TYPE.PRODUCT_SPU_TYPE"
                      :value="row?.spuType"
                      effect="plain"
                      v-else
                    />
                    {{ row.spuName }}
                    <meton-tag
                      :is-dict="false"
                      :is-text="true"
                      :value="`${row.specType ? skuSpecFormat(row?.properties) : ''},${row.spuType == 2 ? filterCardAttributes(row, true, true) : ''}`"
                    />
                  </span>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="price" min-width="85">
          <template #default="{ row }">
            {{ row.count }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="零售单价" prop="price" min-width="100">
          <template #default="{ row }"> {{ floatToFixed2(row.price) }} 元 </template>
        </el-table-column>
        <el-table-column align="center" label="售后状态" prop="afterSaleStatus" min-width="85">
          <template #default="{ row }">
            <dict-tag
              :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
              :value="row.afterSaleStatus"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="实售单价" prop="singlePrice" min-width="100">
          <template #header>
            <div class="flex items-center justify-center">
              实售单价
              <el-popover
                :width="200"
                trigger="hover"
                placement="top"
                :content="NoteOnOrder.SHISHOUDANJIA"
              >
                <template #reference>
                  <Icon icon="ep:warning" class="m-l-2px" />
                </template>
              </el-popover>
            </div>
          </template>
          <template #default="{ row }"> {{ floatToFixed2(row.singlePrice) }} 元 </template>
        </el-table-column>

        <el-table-column align="center" label="订单实售" prop="realPrice" min-width="100">
          <template #header>
            <div class="flex items-center justify-center">
              订单实售
              <el-popover
                :width="200"
                trigger="hover"
                placement="top"
                :content="NoteOnOrder.DINGDANSHISHOU"
              >
                <template #reference>
                  <Icon icon="ep:warning" class="m-l-2px" />
                </template>
              </el-popover>
            </div>
          </template>
          <template #default> {{ floatToFixed2(scope.row.realPrice) }} 元 </template>
        </el-table-column>
        <el-table-column align="center" label="佣金" prop="rebatePrice" min-width="100">
          <template #header>
            <div class="flex items-center justify-center"> 佣金 </div>
          </template>
          <template #default="{ row }"> {{ floatToFixed2(row.rebatePrice) }} 元 </template>
        </el-table-column>

        <el-table-column align="center" label="会员" min-width="100">
          <template #default>
            <div class="flex items-center justify-center">
              <el-text>{{ scope.row?.user?.nickname }}</el-text>
              <el-image
                class="w-26px"
                v-if="scope.row?.user?.activeState == 1"
                src="https://files.meton.vip/6aa306a95ea11ed10973123b535247f84da11d1b385389e6ed5e5f872a67ce07.png"
              />
            </div>

            <el-text class="mt-5px">{{ scope.row?.user?.mobile }}</el-text>
          </template>
        </el-table-column>

        <el-table-column align="center" label="订单状态" min-width="85">
          <template #default>
            <dict-tag :type="DICT_TYPE.TRADE_ORDER_STATUS" :value="scope.row.status" />
            <dict-tag
              class="mt-5px"
              :type="DICT_TYPE.TRADE_ORDER_ITEM_AFTER_SALE_STATUS"
              :value="scope.row.refundStatus"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" min-width="85">
          <template #default>
            <slot :row="scope.row"></slot>
          </template>
        </el-table-column>
      </el-table>
      <ContentWrap
        :bodyStyle="{ padding: '10px', borderRadius: '0px' }"
        class="!border-rd-none !border-t-none"
      >
        <el-row
          class="color-[#606266] dark:bg-[var(--el-bg-color)] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
        >
          <el-col :span="24">
            <div class="flex items-center">
              <!-- 门店下单 不展示配送方式 -->
              <div v-if="scope.row.deliveryType !== DeliveryTypeEnum.SHOP.type">
                <span>配送方式：</span>
                <dict-text
                  :type="DICT_TYPE.TRADE_DELIVERY_TYPE"
                  :value="scope.row.deliveryType"
                  class="mr10px!"
                />
              </div>
              <!-- 门店下单 -->
              <!-- <div v-if="scope.row.deliveryType === DeliveryTypeEnum.SHOP.type">
                <el-text class="mr-10px!">销售门店: {{ scope.row.nodeName }}</el-text>
                <el-text
                  >销售员工:
                  <el-text class="mr-5px!" v-for="item in scope.row.employeeStr" :key="item"
                    >{{ item.employeeName }}({{ item.employeeId }}):{{ item.proportion }}%</el-text
                  ></el-text
                >
              </div> -->
              <!-- 自提 -->
              <div v-if="scope.row.deliveryType === DeliveryTypeEnum.PICK_UP.type">
                <span> 门店:</span>
                <span class="mr10px!">
                  {{ pickUpStoreList.find((p) => p.id === scope.row.pickUpStoreId)?.name }}
                </span>
              </div>
              <!-- 快递发货 -->
              <div v-if="scope.row.deliveryType === DeliveryTypeEnum.EXPRESS.type">
                <span> 收货人: </span>
                <span class="mr10px!">
                  {{ scope.row.receiverName }}
                </span>
                <span> 手机号： </span>
                <span class="mr10px!">
                  {{ scope.row.receiverMobile }}
                </span>
                <span> 地址： </span>
                <span class="mr10px!">
                  {{ scope.row.receiverAreaName }} {{ scope.row.receiverDetailAddress }}
                </span>
                <el-button
                  @click.stop="
                    copyContent(
                      `${scope.row.receiverName} ${scope.row.receiverMobile} ${scope.row.receiverDetailAddress}`
                    )
                  "
                  type="text"
                >
                  <Icon
                    icon="ep:copy-document"
                    :size="14"
                    class="color-[var(--el-color-primary)]"
                  />
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-divider v-if="scope.row.userRemark" border-style="dashed" class="mt-10px! mb-10px!" />
        <el-row
          class="color-[#606266] dark:bg-[var(--el-bg-color)] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
          v-if="scope.row.userRemark"
        >
          <el-col :span="24">
            <div class="flex">
              <div>
                <span> 会员备注： </span>

                <span class="mr10px!">
                  {{ scope.row.userRemark }}
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-divider
          border-style="dashed"
          class="mt-10px! mb-10px!"
          v-if="scope.row?.orderStoreReasons?.length"
        />

        <el-row
          class="color-[#606266] dark:bg-[var(--el-bg-color)] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
          v-if="scope.row?.orderStoreReasons?.length"
        >
          <el-col :span="24">
            <div class="flex" v-if="scope.row.orderStoreReasons.length > 1">
              <div>
                <el-text class="mr-10px!">门店备注: </el-text>
                <div
                  v-for="(item, index) in scope.row.orderStoreReasons"
                  :key="index"
                  class="flex flex-col mt-5px!"
                >
                  <div>
                    {{ item.creator.split(':')[1] }} (ID:{{ item.creator.split(':')[0] }})
                    {{ formatDate(item.createTime) }}【<el-text type="primary"
                      >{{ item.reason }} </el-text
                    >】
                  </div>
                </div>
              </div>
            </div>
            <div class="flex" v-else>
              <div class="flex items-center">
                <el-text>门店备注:</el-text>
                <span
                  v-for="(item, index) in scope.row.orderStoreReasons"
                  :key="index"
                  class="flex flex-col ml-2px"
                >
                  <div>
                    {{ item.creator.split(':')[1] }} (ID:{{ item.creator.split(':')[0] }})
                    {{ formatDate(item.createTime) }}【<el-text type="primary"
                      >{{ item.reason }} </el-text
                    >】
                  </div>
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-divider
          border-style="dashed"
          class="mt-10px! mb-10px!"
          v-if="scope.row?.orderReasons?.length"
        />

        <el-row
          class="color-[#606266] dark:bg-[var(--el-bg-color)] dark:color-[var(--el-text-color-primary)]"
          style="font-weight: normal"
          v-if="scope.row?.orderReasons?.length"
        >
          <el-col :span="24">
            <div class="flex" v-if="scope.row.orderReasons.length > 1">
              <div>
                <el-text class="mr-10px!">总部备注: </el-text>
                <div
                  v-for="(item, index) in scope.row.orderReasons"
                  :key="index"
                  class="flex flex-col mt-5px!"
                >
                  <div>
                    {{ item.creator.split(':')[1] }} (ID:{{ item.creator.split(':')[0] }})
                    {{ formatDate(item.createTime) }}【<el-text type="primary"
                      >{{ item.reason }} </el-text
                    >】
                  </div>
                </div>
              </div>
            </div>
            <div class="flex" v-else>
              <div class="flex items-center">
                <el-text>总部备注:</el-text>
                <span
                  v-for="(item, index) in scope.row.orderReasons"
                  :key="index"
                  class="flex flex-col ml-2px"
                >
                  <div>
                    {{ item.creator.split(':')[1] }} (ID:{{ item.creator.split(':')[0] }})
                    {{ formatDate(item.createTime) }}【<el-text type="primary"
                      >{{ item.reason }} </el-text
                    >】
                  </div>
                </span>
              </div>
            </div>
          </el-col>
        </el-row>
      </ContentWrap>
    </template>
  </el-table-column>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { DeliveryTypeEnum, NoteOnOrder } from '@/utils/constants'
import { formatDate } from '@/utils/formatTime'
import { floatToFixed2, skuSpecFormat } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { OrderVO } from '@/api/mall/trade/order'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { createImageViewer } from '@/components/ImageViewer'
import type { DeliveryPickUpStoreVO } from '@/api/mall/trade/delivery/pickUpStore'
// import { debounce } from 'lodash-es'
import { useProductUtils } from '@/views/mall/product/hooks/useProduct'
const { filterCardAttributes } = useProductUtils()

defineOptions({ name: 'OrderTableColumn' })

const props = defineProps<{
  list: OrderVO[]
  pickUpStoreList: DeliveryPickUpStoreVO[]
}>()

interface SpanMethodProps {
  row: TradeOrderApi.OrderItemRespVO
  column: TableColumnCtx<TradeOrderApi.OrderItemRespVO>
  rowIndex: number
  columnIndex: number
}

type spanMethodResp = number[] | { rowspan: number; colspan: number } | undefined
const spanMethod = ({ row, rowIndex, columnIndex }: SpanMethodProps): spanMethodResp => {
  const len = props.list.find(
    (order) => order.items?.findIndex((item) => item.id === row.id) !== -1
  )?.items?.length
  // 要合并的列，从零开始
  const colIndex = [5, 6, 7, 8, 9, 10, 11]
  if (colIndex.includes(columnIndex)) {
    // 除了第一行其余的不要
    if (rowIndex !== 0) {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
    // 动态合并行
    return {
      rowspan: len!,
      colspan: 1
    }
  }
}

/** 解决 ref 在 v-for 中的获取问题*/
const setOrderTableRef = (el: TableInstance) => {
  if (!el) return
  // 只要第一个表也就是开始的第一行
  // if (el.tableId !== 'el-table_2') {
  //   return
  // }
  // tableHeadWidthAutoDebounce(el)
}
// 头部 col 宽度初始化
// const orderTableHeadWidthList = ref([170, 130, 130, 130, 130, 130, 130, 130, 130, 130])
// 头部宽度自适应
// const tableHeadWidthAutoDebounce = debounce((el: TableInstance) => {
//   tableHeadWidthAuto(el), 500
// }) //计算头部宽度 防抖
// const tableHeadWidthAuto = (el: TableInstance) => {
//   console.log(el)
//   const columns = el.store.states.columns.value
//   if (columns.length === 0) {
//     return
//   }
//   columns.forEach((col: TableColumnCtx<TableInstance>, index: number) => {
//     if (col.realWidth) {
//       orderTableHeadWidthList.value[index] = col.realWidth
//     }
//   })
// }
/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}
const emit = defineEmits(['uploadCertificate', 'setOrderTag'])

/** 复制 */
const message = useMessage() // 消息弹窗
import { useClipboard } from '@vueuse/core'
const { copy } = useClipboard() // 初始化 copy 到粘贴板
const copyContent = async (content) => {
  await copy(content)
  message.success('复制成功！')
}
</script>
<style lang="scss" scoped>
:deep(.table-col-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
</style>
